package com.oocl.ita.sakura.handler;

import java.io.ObjectOutputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.oocl.ita.sakura.client.Client;
import com.oocl.ita.sakura.forwarder.Forwarder;
import com.oocl.ita.sakura.ioutil.NetIOUtil;
import com.oocl.ita.sakura.protocol.Protocol;
import com.oocl.ita.sakura.server.IMServer;

public class LoginHandler implements IHandler{

	/*
	 * (non-Javadoc)
	 * @see com.oocl.ita.sakura.handler.IHandler#handle(com.oocl.ita.sakura.protocol.Protocol)
	 * 
	 * 1. use case : 接受login报文，在服务器中增加一个Client。 
	 * {
	 * 	"msgType" : "login",
	 * "from" : Client,
	 * }
	 * 
	 * 1.5 重复登录？
	 * 
	 * 2. 封装新的syn报文发送给所有人
	 * {
	 * "msgType" : "syn",
	 * "list" : list<Client>
	 * }
	 */
	@Override
	public void handle(Protocol protocol) {
		// debug
		System.out.println("LoginHandler: Login" + Thread.currentThread().getName());
		
		// pre-process 
		// IMServer.ClientOOSMap 增加用户
		Client loginClient = (Client)protocol.getParams().get("from");
        ObjectOutputStream oos = (ObjectOutputStream) Forwarder.threadlocaloos.get();
		Forwarder.threadlocalClient.set(loginClient);
        IMServer.addClient(loginClient, oos);
		
		// encapsulation 封装一个报文
		Map<String, Object> params = new HashMap();
		List<Client> listClient = new ArrayList<Client>(IMServer.getClientOosMap().keySet());
		params.put("list", listClient);
		if (listClient == null) {
			System.out.println("LoginHandler : listClient is null");
		}
		Protocol retProtocol = new Protocol("syn", params);
		
		// send  同步
		// 工具类，不在这里抛出异常而已。。。
		NetIOUtil.send(retProtocol, new Client("all"));
		System.out.println("LoginHanlder : synProtocol" + retProtocol);
		System.out.println("LoginHandler Done");
	}

}
